﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Camera;
using ZK.Common;
using ZK.Common.ProModels;
using ZK.HardWareHelper;
using ZK.InfraredGrating;
using ZK.WagonBalance;

namespace ZK.CoalYardTransManage
{
    public partial class RemovalAndWeigh : Form
    {

        #region 属性
        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();
        bool cameraIsOpen = false;
        private Camera.Camera camera;
        private Int32 m_lUserID = -1;//用户id
        private uint iLastErr = 0;//错误代码
        private string str = "";//错误信息
        private Int32 m_lRealHandle = -1;//预览状态
        private bool m_bInitSDK = false;//初始化摄像头状态
        private delegate void ChangedHandler_ReadedTransInfo(TransBasicInfo model, EventArgs e);//带参委托
        private static event ChangedHandler_ReadedTransInfo Change_ReadedTransInfo;//委托事件
        private int InfraredGratingDate;
        private Camera.Camera cameraMonitor = null;
        /// <summary>
        /// 红外返回0 3 的时候算是正常数据
        /// </summary>
        readonly int[] Interfered = new int[] { 0, 3 };
        //private ILed ledEnter;
        private WagonBalance.WagonBalance wagonBalance;
        //磅秤重量列表，根据列表中n组数据判断当前磅秤是否稳定。
        private List<double> weighList = new List<double>();
        /// <summary>
        /// 指定磅秤返回的数据列表中的最大个数。
        /// </summary>
        private int weighListCount = Convert.ToInt32(AppConfigHelper.GetAppSettings("weighListCount"));

        private Thread loadHwThread;
        private double weighNow = 0;
        //private Thread wagonThread;
        /// <summary>
        /// 重量标准（单位吨）
        /// </summary>
        private double weighPK = Convert.ToDouble(AppConfigHelper.GetAppSettings("weighPK"));
        /// <summary>
        /// 车牌以及车牌识别的摄像头序号集合
        /// </summary>
        private Dictionary<string, int> carNumList = new Dictionary<string, int>();
        private delegate void ChangedHandler_ReadedTare(decimal tareQuantity, EventArgs e);
        private static event ChangedHandler_ReadedTare Change_ReadedTare;

        private delegate void ChangedHandler_ReadedRealTare(decimal realTare, EventArgs e);
        private static event ChangedHandler_ReadedRealTare Change_ReadedRealTare;

        private delegate void ChangedHandler_ReadedRealGrossWeight(decimal realGrossWeight, EventArgs e);
        private static event ChangedHandler_ReadedRealGrossWeight Change_ReadedRealGrossWeight;

        private static bool isInfraredStatus = false; //红外光栅是否正常

        private List<TruckData> listTruckData = null;

        private List<CardData> listCardData = null;

        //private readonly List<InfraredGrating.InfraredGrating> _infraredGratings;
        private readonly Dictionary<string, string> _infraredGratingData;

        private List<decimal> listWeight = null;
        private List<decimal> listWeight_copy = null;
        private List<decimal> listRealQuantity = null;

        //地磅重量稳定计算的timer
        private System.Timers.Timer weightTimer = null;

        private string errorStr = string.Empty;

        private static int truckState = 0;

        private int weighType = Settings.GetInt("WeighType");

        private string ledMsg = string.Empty;

        private CameraSetup monitorSetup = null;

        private bool isOverload = false;    //是否超重

        private decimal baseTare = 0;

        private decimal ratedLoad = 0;

        private decimal weightFloatingMz = 0;

        private decimal weightFloatingPz = 0;

        private List<EnteredTruckModel> ListEnteredTruck;


        private static TruckYxInfo truckYxInfo = null;
        //private static TransBasicInfo TransInfo
        //{
        //    get { return transInfo; }
        //    set
        //    {
        //        transInfo = value;
        //        Change_ReadedTransInfo?.Invoke(transInfo, null);
        //    }
        //}

        private SysDefinitionEnum.YxState yx_State;
        private string cardNum = "";
        private string truckNum = "";
        bool IsOpenVideo = false;
        private decimal realTare = 0;
        private decimal RealTare
        {
            get
            {
                return realTare;
            }
            set
            {
                realTare = value;
                listRealQuantity.Add(value);
                Change_ReadedRealTare?.Invoke(realTare, null);
            }
        }
        private decimal realGrossWeight = 0;
        private decimal RealGrossWeight
        {
            get
            {
                return realGrossWeight;
            }
            set
            {
                realGrossWeight = value;
                listRealQuantity.Add(value);
                Change_ReadedRealGrossWeight?.Invoke(realGrossWeight, null);
            }
        }
        private static decimal tareQuantity = 0;
        private static decimal TareQuantity
        {
            get
            {
                return tareQuantity;
            }
            set
            {
                tareQuantity = value;
                Change_ReadedTare?.Invoke(tareQuantity, null);
            }
        }
        private bool isRedLight = false;
        private decimal grossWeight = 0;
        private Led.ILed led;
        CameraHelper cameraHelperG = new CameraHelper(3);//初始化后摄像头
        CameraHelper cameraHelperH = new CameraHelper(2);//初始化后摄像头
        CameraHelper cameraHelperQ = new CameraHelper(1);//初始化前摄像头
        LEDHelper lEDHelperQ = new LEDHelper();//初始化前摄像头
        LEDHelper lEDHelperH = new LEDHelper();//初始化前摄像头
        /// <summary>
        /// 实例化一个红外对象。
        /// </summary>
        InfraredGratingHelper infraredGratingHelper;

        string pictureId = "";//图片上传之后的id
        /// <summary>
        /// 皮重
        /// </summary>
        /// <returns></returns>
        decimal pz()
        {
            if (string.IsNullOrWhiteSpace(lbTareQuantity.Text.Trim()))
            {
                return 0;
            }
            else
            {
                return Convert.ToDecimal(lbTareQuantity.Text.Trim());
            }
        }
        /// <summary>
        /// 毛重
        /// </summary>
        /// <returns></returns>
        decimal mz()
        {
            if (string.IsNullOrWhiteSpace(lbTareQuantity.Text.Trim()))
            {
                return 0;
            }
            else
            {
                return Convert.ToDecimal(lbTareQuantity.Text.Trim());
            }
        }
        /// <summary>
        /// 扣吨数
        /// </summary>
        /// <returns></returns>
        //decimal kds()
        //{
        //    if (string.IsNullOrWhiteSpace(txtTonnageDeduction.Text.Trim()))
        //    {
        //        return 0;
        //    }
        //    else
        //    {
        //        return Convert.ToDecimal(txtTonnageDeduction.Text.Trim());
        //    }
        //}
        /// <summary>
        /// weighId  （地磅id）
        /// </summary>
        int wgbId = Convert.ToInt32(AppConfigHelper.GetAppSettings("weighId"));//weighId
        /// <summary>
        /// bunkerId （仓料id）
        /// </summary>
        int bunkerId = Convert.ToInt32(AppConfigHelper.GetAppSettings("bunkerId"));//bunkerId
        #endregion
        /// <summary>
        /// 初始化页面
        /// </summary>
        public RemovalAndWeigh()
        {
            InitializeComponent();
            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
            DelegateHelper.EventGetCarNum += GetCarNum;
        }
        #region 设置车牌号-委托-事件

        /// <summary>
        /// 获取车牌号-委托-事件
        /// </summary>
        /// <param name="carNum"></param>
        /// <param name="order">摄像头顺序（1对外，2对地磅。）</param>
        private void GetCarNum(string carNum, int order)
        {
            if (carNumList.Where(p => p.Key == carNum).Count() == 0)
            {
                carNumList.Add(carNum, order);
                // orderOfCamera = order;
                //string carNumNow = txtCarNum.Text.Trim();
                //if (true)
                //{
                //}
                //if (string.IsNullOrWhiteSpace(carNumNow))
                //{
                //    SetCarNum();
                //}

                if ((Convert.ToDecimal(lbTareQuantity.Text.Trim()) <= 0) || (order == 2))
                {
                    SetCarNum();
                }
            }

            // btnQuery_Click(null, null);
        }
        #endregion
        /// <summary>
        /// 小车通行
        /// </summary>
        void LittleCarRun()
        {
        }
        /// <summary>
        /// 设置车牌（显示出来）没有了，设置为空
        /// </summary>
        private void SetCarNum()
        {
            this.Invoke(new Action(() =>
            {

                string carNum = txtCarNum.Text.Trim();

                if (!string.IsNullOrWhiteSpace(carNum))
                {
                    var carNumTemp = carNumList.Where(p => p.Key == carNum).FirstOrDefault();
                    if (!string.IsNullOrWhiteSpace(carNumTemp.Key ?? ""))
                    {

                        //if (carNumTemp.Value == 2  && labelMessageShow.ForeColor == Color.Green)
                        //{
                        //    OpenMen();
                        //}
                        carNumList.Remove(carNumTemp.Key);

                    }
                    ClearText();
                    if (carNumList.Count > 0)
                    {
                        var carNumOne = carNumList.FirstOrDefault();
                        txtCarNum.Text = carNumOne.Key;
                        txtCoalsCarNum.Text = carNumOne.Key;
                        ShowLedClient("当前车辆：" + carNumOne.Key, EnumHelper.LCCWLX.information);
                        //if (carNumOne.Value == 1) OpenMen();
                        btnQuery_Click_1(null, null);

                    }
                    else
                    {
                        txtCarNum.Text = "";
                        txtCoalsCarNum.Text = "";
                        //btnClear_Click(null, null);
                        ShowLedClient(TipsStringHelper.hxmchyn, EnumHelper.LCCWLX.information);
                    }
                }
                else
                {
                    if (carNumList.Count > 0)
                    {
                        var carNumOne = carNumList.FirstOrDefault();
                        txtCarNum.Text = carNumOne.Key;
                        txtCoalsCarNum.Text = carNumOne.Key;
                        ShowLedClient("当前车辆：" + carNumOne.Key, EnumHelper.LCCWLX.information);
                        // if (carNumOne.Value == 1) OpenMen();
                        btnQuery_Click_1(null, null);

                    }
                    else
                    {
                        txtCarNum.Text = "";
                        txtCoalsCarNum.Text = "";
                        //btnClear_Click(null, null);
                        ShowLedClient(TipsStringHelper.hxmchyn, EnumHelper.LCCWLX.information);
                    }
                }





            }));
        }
        /// <summary>
        /// form加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemovalAndWeigh_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            labelDQYH.Text = "当前用户：" + AppSession.UserInfo.UserName;
            //多线程初始化硬件
            ThreadStart hwThead = new ThreadStart(InitHardWare);
            loadHwThread = new Thread(hwThead);
            loadHwThread.IsBackground = true;
            loadHwThread.Start();


        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadByConfig()
        {
            if (!IsOpenVideo)
            {
                //btnVideoOpera.Text = "打开视频";
            }
            else
            {
                //btnVideoOpera.Text = "关闭视频";
            }
        }
        /// <summary>
        /// 线程启动相关硬件初始化
        /// </summary>
        /// <returns></returns>
        private void InitHardWare()
        {
            //红外初始化
            infraredGratingHelper = new InfraredGratingHelper();
            infraredGratingHelper.Open();

            //高空摄像头
            this.Invoke(new Action(() =>
            {
                cameraHelperG.ManualOne(pictureBoxG);
                cameraIsOpen = true;
            }));
            //led两个
            lEDHelperQ.LedSmallInitialize(1);
            lEDHelperH.LedSmallInitialize(2);

            //地磅
            SerialPortConfig config = new SerialPortConfig()
            {
                Name = MyCustomConfig.wagonBalanceConfig.Name,
                PortName = MyCustomConfig.wagonBalanceConfig.PortName,
                BaudRate = MyCustomConfig.wagonBalanceConfig.BaudRate,
                DataBits = MyCustomConfig.wagonBalanceConfig.DataBits
            };
            wagonBalance = new WagonBalance.WagonBalance(config);
            wagonBalance.WeightCallback += EventWeightBack;

            DelegateHelper.InfraredGratingEvent += InfraredGratingEvent1;//红外光栅委托
        }

        private void InfraredGratingEvent1(int data)
        {
            InfraredGratingDate = data;
        }

        /// <summary>
        /// 判断车辆是否下磅。
        /// </summary>
        private bool judgeDown = false;


        /// <summary>
        /// 地磅上是否有过数据
        /// </summary>
        private bool DBSFYGSJ = false;
        /// <summary>
        /// 在查询之后显示磅秤的重量。
        /// </summary>
        private bool ShowWeigh = true;
        /// <summary>
        /// 获取地磅数据
        /// </summary>
        /// <param name="weight"></param>
        private void EventWeightBack(double weight)
        {

            weighList.Add(weight);
            if (weighList.Count > weighListCount)
            {
                weighList.RemoveAt(0);
            }

            //判断是否下磅
            //if ((weight >= 0) && (weight < weighPK) && carNumList.Count>0)
            var carNow = carNumList.FirstOrDefault();
            //if (!string.IsNullOrEmpty(carNow.Key))
            //{

            //}
            if ((weight == 0) && SFYXXB && DBSFYGSJ)
            {
                DBSFYGSJ = false;
                // judgeDown = true;
                SetCarNum();
                SFYXXB = false;
                ShowWeigh = true;

            }

            this.Invoke(new Action(() =>
            {
                // txtTare.Text = weight.ToString();

                if (weight >= 0)
                {

                    lbTareQuantity.Text = weight.ToString();
                    lbCoalsTareQuantity.Text = weight.ToString();
                }

            }));


            if (ShowWeigh && weighList.Count >= weighListCount)
            {

                double PJTemp = Math.Round(weighList.Average(), 2);
                if (weighList.Where(t => t == PJTemp).Count() == weighListCount && (PJTemp > weighPK))
                {
                    DBSFYGSJ = true;
                    ShowLedClient(TipsStringHelper.dqzl + PJTemp + "吨", EnumHelper.LCCWLX.information);
                    ShowWeigh = false;
                }
            }


            // weighList.Add(weight);
            //if (weighList.Count > weighListCount)
            //{
            //    weighList.RemoveAt(0);
            //    decimal PJTemp = weighList.Average();
            //    if (weighList.Where(t => t == PJTemp).Count() == weighListCount &&(PJTemp > weighPK))
            //    {
            //        string carNum = txtCarNum.Text.Trim();
            //        if (judgeDown)
            //        {
            //            if ( !string.IsNullOrWhiteSpace(carNum))
            //            {
            //                judgeDown = false;
            //                btnQuery_Click(null, null);
            //            }
            //        }
            //        else
            //        {
            //            if (!string.IsNullOrWhiteSpace(carNum))
            //            {
            //                SetCarNum();
            //            }
            //        }

            //    }
            //}

            // }

        }

        void ShowWeighFun()
        {
            if (ShowWeigh)
            {
                double PJTemp = Math.Round(weighList.Average(), 2);

            }
        }

        /// <summary>
        /// form关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemovalAndWeigh_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
                e.Cancel = true;
            this.Hide();
        }
        /// <summary>
        /// Icon图标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void projectIcon_Click_1(object sender, EventArgs e)
        {
            this.Show();
        }
        #region 清空按钮事件
        /// <summary>
        /// 清空按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click_1(object sender, EventArgs e)
        {
            try
            {
                carNumList.Remove(txtCarNum.Text);
                // ClearText();
                // SetCarNum();
                SFYXXB = true;
                ShowLedClient(TipsStringHelper.hxmchyn, EnumHelper.LCCWLX.information);
                this.Invoke(new Action(() => { txtCarNum.Text = ""; }));
                ClearText();
            }
            catch (Exception ex)
            {
                _Led_Messahge_Log(ex);
                // Thread.Sleep(2000);
                return;
            }
        }
        #endregion
        /// <summary>
        /// 清除数据方法
        /// </summary>
        void ClearText()
        {
            HideCPCZ();
            Print.TruckYxInfo = new TruckYxInfo();
            Invoke(new Action(() =>
            {
                txtCarNum.Text = "";//运销车牌号清空
                txtCoalsCarNum.Text = "";//盘煤车牌号清空
                txtCarType.Text = "";
                txtCoalType.Text = "";
                txtTransType.Text = "";
                txtRatedLoad.Text = "";
                txtTransportUnit.Text = "";
                txtReceivingUnit.Text = "";
                txtForwardingUnit.Text = "";
                txtTare.Text = "";
                textBoxKFL.Text = "";
                textBoxKD.Text = "";
                //txtTonnageDeduction.Text = "";
                txtGrossWeight.Text = "";
                // txtdeliveringAmount.Text = "";
                // txtWeighName.Text = "";
                // txtWeighTime.Text = "";
                // lbTareQuantity.Text = "0.0";

            }));
        }
        #region 打开视频
        /// <summary>
        /// 打开视频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenVideo1_Click(object sender, EventArgs e)
        {
            string ip = "192.168.3.64";
            var res = cameraHelperQ.ManualOne(picVideo1, ip);
            if (!res.res)
                ShowMessageAndLed(res.Msg, "打开视频");
            else
            {
                ClientShowMessage("视频打开成功", EnumHelper.LCCWLX.information);
            }

        }
        #endregion

        #region MyRegion
        private void RealDataCallBack(int lRealHandle, uint dwDataType, ref byte pBuffer, uint dwBufSize, IntPtr pUser)
        {
        }
        #endregion


        /// <summary>
        /// show cp 
        /// </summary>
        private void ShowCP()
        {
            this.Invoke(new Action(() =>
            {
                btnWeigh.Hide();
                btnSkinRemoval.Show();
            }));

        }
        /// <summary>
        /// show cp and cz
        /// </summary>
        private void HideCPCZ()
        {
            this.Invoke(new Action(() =>
            {
                btnWeigh.Hide();
                btnSkinRemoval.Hide();
            }));

        }
        /// <summary>
        /// show cz
        /// </summary>
        private void ShowCZ()
        {
            this.Invoke(new Action(() =>
            {
                btnSkinRemoval.Hide();
                btnWeigh.Show();
            }));

        }

        #region 查询按钮
        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click_1(object sender, EventArgs e)
        {
            try
            {
                // JudgeCheckZD();
                //红外打开
                //infraredGratingHelper.Open();

                //weighNow = Convert.ToDecimal(lbTareQuantity.Text.Trim());
                //ShowLed("当前重量：" + weighNow);
                ////判断车辆重量是否达标
                //if (weighNow<weighPK)
                //{
                //    MessageThrow(TipsStringHelper.zlbdb, "重量");
                //}
                //Thread.Sleep(3000);
                HideCPCZ();
                string carNum = txtCarNum.Text.Trim();
                if (string.IsNullOrWhiteSpace(carNum))
                {
                    MessageThrow(TipsStringHelper.cphbnwk, "车牌号");
                }
                KeyValuePair<string, int> carNumTemps = carNumList.FirstOrDefault();
                //判断车牌是否识别错误并修改，如果是，需要更新列表中的数据
                if (carNumList.Where(p => p.Key == carNum).Count() == 0)
                {
                    carNumList.Remove(carNumTemps.Key ?? "");
                    carNumList.Add(carNum, carNumTemps.Value);
                }

                //if (carNumList.Where(p => p.Key == carNum).Count() == 0)
                //{
                //    //var carNumTemps = carNumList.FirstOrDefault();
                //    carNumList.Remove(carNumTemps.Key ?? "");
                //    carNumList.Add(carNum, carNumTemps.Value);
                //}

                ///获取车辆信息
                ResultDataBase<TruckYxInfo> resultDataBase = WebApiService.GetTruckYxInfo(carNum);
                if (resultDataBase == null)
                    MessageThrow(TipsStringHelper.xtfhsjwk + "BASE", "车辆信息");
                if (!resultDataBase.success)
                    MessageThrow(resultDataBase.msg, "车辆信息");
                if (resultDataBase.data == null)
                    MessageThrow(TipsStringHelper.xtfhsjwk + "DATA", "车辆信息");
                truckYxInfo = resultDataBase.data;
                //车辆信息赋值
                Print.TruckYxInfo = resultDataBase.data;
                if (truckYxInfo.sendType == SysDefinitionEnum.SendType.采购)
                {

                    if (truckYxInfo.yxState == SysDefinitionEnum.YxState.除皮_收 ||
                        truckYxInfo.yxState == SysDefinitionEnum.YxState.卸车_收
                        )
                    {
                        ShowCP();
                    }
                    if (truckYxInfo.yxState == SysDefinitionEnum.YxState.派车 ||
                        truckYxInfo.yxState == SysDefinitionEnum.YxState.入场_收 ||
                        truckYxInfo.yxState == SysDefinitionEnum.YxState.称重_收
                        )
                    {
                        ShowCZ();
                    }

                }
                else
                {
                    if (
                         truckYxInfo.yxState == SysDefinitionEnum.YxState.装车_发 ||
                         truckYxInfo.yxState == SysDefinitionEnum.YxState.称重_发

                        )
                    {
                        ShowCZ();
                    }
                    if (truckYxInfo.yxState == SysDefinitionEnum.YxState.派车 ||
                         truckYxInfo.yxState == SysDefinitionEnum.YxState.入场_发 ||
                          truckYxInfo.yxState == SysDefinitionEnum.YxState.除皮_发
                        )
                    {
                        ShowCP();
                    }
                }
                //ShowLed("当前车辆：" + truckYxInfo.truckNo);

                //infrared operations (红外判断是否有遮挡)
                //InfraredO();
                //get weigh from weighing

                ///盘煤跳转导航
                if (truckYxInfo.truckState == SysDefinitionEnum.TruckState.盘煤)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.tabMain.SelectedIndex = 1;
                        txtCoalsCarNum.Text = txtCarNum.Text;
                    }));
                    //盘煤 turn coal
                    //TurnCoal();
                }
                else
                {
                    SetText();
                    //入场
                    if (truckYxInfo.yxState == SysDefinitionEnum.YxState.派车)
                    {
                        //截图
                        //pictureId = JQYSSC();
                        //if (string.IsNullOrWhiteSpace(pictureId))
                        //{
                        //    MessageThrow(TipsStringHelper.tpclyc, "图片处理");
                        //}
                        carIn();
                        // OpenMen();

                    }
                    if ((truckYxInfo.yxState == SysDefinitionEnum.YxState.出场_发) || (truckYxInfo.yxState == SysDefinitionEnum.YxState.出场_收))
                    {

                        //SetCarNum();
                        OpenMen();
                    }

                    //销售采购  sale&purchase
                    ///Salepurchase();
                }
                //ShowLed(TipsStringHelper.hxmchyn);
                //infraredGratingHelper.Close();
                // Thread.Sleep(3000);
                // SetCarNum();
                if (carNumTemps.Value == 1)
                {
                    OpenMen();

                }
                ShowLedClient(TipsStringHelper.dqcl + carNum, EnumHelper.LCCWLX.information);
            }
            catch (Exception ex)
            {
                //infraredGratingHelper.Close();
                _Led_Messahge_Log(ex);
                // Thread.Sleep(2000);
                return;
            }
        }
        #endregion
        /// <summary>
        /// 设置车辆信息
        /// </summary>
        private void SetText()
        {
            if (truckYxInfo == null)
                truckYxInfo = new TruckYxInfo();
            this.Invoke(new Action(() =>
            {
                this.tabMain.SelectedIndex = 0;
                ///车辆信息赋值
                txtCoalType.Text = truckYxInfo.coalName;//煤种
                txtTransType.Text = Enum.GetName(typeof(SysDefinitionEnum.TruckState), truckYxInfo.truckState) + "-" + Enum.GetName(typeof(SysDefinitionEnum.YxState), truckYxInfo.yxState);      //运销类型
                txtCarType.Text = truckYxInfo.truckType;//车型
                txtRatedLoad.Text = truckYxInfo.ratedLoad.ToString();//限重
                txtTransportUnit.Text = truckYxInfo.carrierName;//承运单位
                txtReceivingUnit.Text = truckYxInfo.receivingPartyName;//收货单位
                txtForwardingUnit.Text = truckYxInfo.shipperName;//发货单位
                textBoxKFL.Text = truckYxInfo.coalmineOutput.ToString();//矿发量
                textBoxKD.Text = truckYxInfo.buckleWeight.ToString();//扣吨
                txtTare.Text = truckYxInfo.pz.ToString();
                txtGrossWeight.Text = truckYxInfo.mz.ToString();
            }));
        }
        /// <summary>
        /// open (打开道闸)
        /// </summary>
        private void OpenMen()
        {
            if (AppConfigHelper.GetAppSettings("HaveMen") == "1")
            {
                cameraHelperQ.BarrierGateControl(cmdFlag: 1);
            }
        }
        #region turn coal (盘煤)
        /// <summary>
        /// turn coal (盘煤)
        /// </summary>
        private void TurnCoal()
        {
            infraredGratingHelper.Open();
            weighNow = Convert.ToDouble(lbTareQuantity.Text.Trim());
            ShowLedClient("盘煤重量：" + weighNow + "吨", EnumHelper.LCCWLX.information);
            Thread.Sleep(3000);
            //判断车辆重量是否达标
            if (weighNow < weighPK)
            {
                MessageThrow(TipsStringHelper.zlbdb, "重量");
            }
            string truckNo = "";
            this.Invoke(new Action(() =>
            {
                truckNo = txtCoalsCarNum.Text.Trim();
                textMZ.Text = weighNow.ToString();
            }));

            if (string.IsNullOrEmpty(truckNo))
            {
                MessageThrow(TipsStringHelper.cphbnwk, "车牌号");
            }

            //judge turn coal (判断是否盘煤车辆)
            var resSeleModel = WebApiService.SelectTruckState(truckNo: truckNo, cardNo: "");//card number is null (卡号暂时为空)
            if (resSeleModel.msg != "此车已是盘煤车辆")
            {
                MessageThrow(resSeleModel.msg, "盘煤车辆");
            }
            this.Invoke(new Action(() =>
            {
                textYPML.Text = string.IsNullOrWhiteSpace(resSeleModel.data) ? "0" : resSeleModel.data;
            }));


            var resInserModel = WebApiService.InsertCoalWeight(new SendPlanCoalweightDto()
            {
                truckNo = truckNo,
                mz = GetWeighData()
            });
            if (!resInserModel.success)
            {
                SFYXXB = true;
                MessageThrow(resInserModel.msg, "盘煤过磅");
            }
            //拿到返回的总量跟剩余量，显示出来
            this.Invoke(new Action(() =>
            {
                //textZL.Text = resInserModel.data.mzAllWeight.ToString();
                textYPML.Text = resInserModel.data.finishWeight.ToString();
            }));

        }
        #endregion
        /// <summary>
        /// 错误信息弹窗，终止流程抛出异常
        /// </summary>
        /// <param name="str"></param>
        /// <param name="title"></param>
        void MessageThrow(string str, string title)
        {
            //MessageBox.Show(str, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
            // LogHelper.LogDebug(str + title);
            throw new Exception(str + "|" + title);
        }

        /// <summary>
        /// 错误信息弹窗并显示led
        /// </summary>
        /// <param name="str"></param>
        /// <param name="title"></param>
        void ShowMessageAndLed(string str, string title)
        {
            // ClientShowMessage(str, EnumHelper.LCCWLX.warning);
            // MessageBox.Show(str, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
            ShowLedClient(str, EnumHelper.LCCWLX.warning);
        }
        /// <summary>
        /// 显示在led上
        /// </summary>
        /// <param name="str"></param>
        void ShowLed(string str)
        {
            lEDHelperH.LedPaly(str);
            lEDHelperQ.LedPaly(str);

        }
        /// <summary>
        /// 显示led，客户端信息
        /// </summary>
        /// <param name="str"></param>
        /// <param name="cCWLX"></param>
        void ShowLedClient(string str, EnumHelper.LCCWLX cCWLX)
        {
            lEDHelperH.LedPaly(str);
            lEDHelperQ.LedPaly(str);
            ClientShowMessage(str, cCWLX);
        }
        #region 自动流程操作
        /// <summary>
        /// 自动流程操作
        /// </summary>
        private void Salepurchase()
        {
            truckYxInfo = WebApiService.GetTruckYxInfo(truckYxInfo.truckNo)?.data;
            if (truckYxInfo == null)
            {
                MessageThrow(TipsStringHelper.clxxyw, "车辆");
            }
            switch (truckYxInfo.yxState)
            {
                //case SysDefinitionEnum.YxState.派车:
                //    carIn();
                //    break;
                case SysDefinitionEnum.YxState.入场_发:
                    SetCutTare();
                    CutTare();
                    // CarLoading();
                    break;
                case SysDefinitionEnum.YxState.除皮_发:
                    SetCutTare();
                    CutTare();
                    // CarLoading();
                    break;
                case SysDefinitionEnum.YxState.装车_发:
                    SetGetWeigh();
                    //CarLoading();
                    GetWeigh();
                    CreateList();
                    CarOut();
                    break;
                case SysDefinitionEnum.YxState.称重_发:
                    SetGetWeigh();
                    GetWeigh();
                    CreateList();
                    CarOut();
                    break;
                case SysDefinitionEnum.YxState.出场_发:
                    SetGetWeigh();
                    CarOut();
                    break;

                case SysDefinitionEnum.YxState.入场_收:
                    SetGetWeigh();
                    GetWeigh();
                    // UnloadGoods();
                    break;
                case SysDefinitionEnum.YxState.称重_收:
                    SetGetWeigh();
                    GetWeigh();
                    // UnloadGoods();
                    break;
                case SysDefinitionEnum.YxState.卸车_收:
                    SetCutTare();
                    // UnloadGoods();
                    CutTare();
                    CreateList();
                    CarOut();
                    break;
                case SysDefinitionEnum.YxState.除皮_收:
                    SetCutTare();
                    CutTare();
                    CreateList();
                    CarOut();
                    break;

                case SysDefinitionEnum.YxState.出场_收:
                    SetCutTare();
                    CarOut();
                    break;

                case SysDefinitionEnum.YxState.生成榜单_发:
                case SysDefinitionEnum.YxState.生成榜单_收:
                    CarOut();
                    break;
                default:
                    MessageThrow(TipsStringHelper.clxxyw, "车辆运销状态");
                    return;
                    // break;
            }

        }
        #endregion

        #region set cut tare (设置除皮信息)
        /// <summary>
        /// set cut tare (设置除皮信息)
        /// </summary>
        public void SetCutTare()
        {
            this.Invoke(new Action(() =>
            {
                txtTare.Text = weighNow.ToString();
            }));
        }
        #endregion

        #region set get weigh (设置称重信息)
        /// <summary>
        /// set get weigh (设置称重信息)
        /// </summary>
        public void SetGetWeigh()
        {
            this.Invoke(new Action(() =>
            {
                txtGrossWeight.Text = weighNow.ToString();
                ;
            }));

        }
        #endregion

        #region weighing data (地磅数据)
        /// <summary>
        /// weighing data (地磅数据)
        /// </summary>
        /// <returns></returns>
        public double GetWeighData()
        {
            return weighNow;
        }
        #endregion

        #region 车辆入场-操作
        /// <summary>
        /// 车辆入场
        /// </summary>
        private void carIn()
        {
            SendTruckAdmissionDto sendTruckAdmissionDto = new SendTruckAdmissionDto()
            {
                cardNo = truckYxInfo.cardNo,
                truckNo = truckYxInfo.truckNo,
                imgs1 = pictureId,
                bfId = Convert.ToInt32(AppConfigHelper.GetAppSettings("bfId"))
            };
            ResultDataBase<string> reRC = WebApiService.TruckAdmission(sendTruckAdmissionDto);
            if (!reRC.success)
            {
                MessageThrow(reRC.msg, "入场");
            }

        }
        #endregion

        #region 除皮操作
        /// <summary>
        /// 除皮操作
        /// </summary>
        private void CutTare()
        {
            var pzRes = WebApiService.TruckTare(new SendTruckTareDto()
            {
                cardNo = truckYxInfo.cardNo,
                imgs1 = pictureId,
                pz = weighNow,
                truckNo = truckYxInfo.truckNo,
                wgbid = Convert.ToInt32(wgbId),
                mz = Convert.ToDouble(txtGrossWeight.Text.Trim() == "" ? "0" : txtGrossWeight.Text.Trim()),
                coalmineOutput = Convert.ToDouble(textBoxKFL.Text.Trim() == "" ? "0" : textBoxKFL.Text.Trim())
            });
            if (!pzRes.success)
            {
                MessageThrow(pzRes.msg, "除皮");
            }
        }
        #endregion

        #region 称重-操作
        /// <summary>
        /// 称重-操作
        /// </summary>
        private void GetWeigh()
        {
            var czRes = WebApiService.TruckWeigh(truckYxInfo.cardNo, pictureId, truckYxInfo.truckNo, weighNow, Convert.ToInt32(wgbId));
            if (!czRes.success)
            {
                MessageThrow(czRes.msg, "称重");
            }
        }
        #endregion

        #region  卸货-操作
        /// <summary>
        /// 卸货-操作
        /// </summary>
        private void UnloadGoods()
        {
            //unload goods
            var xcRes = WebApiService.TruckUnloading(new SendTruckUnloadingDto
            {
                imgs1 = pictureId,
                cardNo = truckYxInfo.cardNo,
                truckNo = truckYxInfo.truckNo,
                // buckleWeight = kds(),
                buckleWeightReason = " ",
                bunkerId = bunkerId,
                memo = " "
            });
            if (!xcRes.success)
            {
                MessageThrow(xcRes.msg, "卸车");
            }
        }
        #endregion

        #region 生成榜单-操作
        /// <summary>
        /// 生成榜单
        /// </summary>
        private void CreateList()
        {
            //creat list
            var scbdRes = WebApiService.TruckWeightBill(truckYxInfo.cardNo, truckYxInfo.truckNo);
            if (!scbdRes.success)
            {
                MessageThrow(scbdRes.msg, "生成榜单");
            }
        }
        #endregion

        #region 车辆出厂-操作
        /// <summary>
        /// 车辆出厂
        /// </summary>
        public void CarOut()
        {
            //leave factory area
            var ccRes = WebApiService.TruckExit(truckYxInfo.cardNo, pictureId, truckYxInfo.truckNo);
            if (!ccRes.success)
            {
                MessageThrow(ccRes.msg, "出场");
            }
        }
        #endregion

        #region 红外感应-操作
        /// <summary>
        /// 红外感应
        /// </summary>
        private void InfraredO()
        {

            //// Thread.Sleep(100);
            int hwNum = InfraredGratingDate;
            Common.Log4.LogManage.WriteWarn("接收到的红外数据：" + hwNum);
            //// infraredGratingHelper.Close();
            //while (hwNum != 3)
            //{
            //    Thread.Sleep(1000);
            //    hwNum = infraredGratingHelper.res;
            //    switch (hwNum)
            //    {
            //        case 1:
            //            //ShowMessageAndLed(TipsStringHelper.rkhwgsyzd, "红外光栅");
            //            ShowLedClient(TipsStringHelper.rkhwgsyzd, EnumHelper.LCCWLX.warning);
            //            break;
            //        case 2:
            //            // ShowMessageAndLed(TipsStringHelper.ckgsyzd, "红外光栅");
            //            ShowLedClient(TipsStringHelper.ckgsyzd, EnumHelper.LCCWLX.warning);
            //            break;
            //        default:
            //            break;
            //    }
            //}

            if (!Interfered.Contains(hwNum))
            {
                Thread.Sleep(1000);
                ShowMessageAndLed(TipsStringHelper.hwgsyzl, "红外光栅");
                InfraredO();

            }
        }
        #endregion

        #region 装车-操作
        /// <summary>
        /// 装车
        /// </summary>
        private void CarLoading()
        {
            var zcRes = WebApiService.TruckLoading(truckYxInfo.cardNo, pictureId, truckYxInfo.truckNo, bunkerId, "");
            if (!zcRes.success)
            {
                MessageThrow(zcRes.msg, "装车");
            }
        }
        #endregion

        #region 称重按钮事件
        /// <summary>
        /// 称重按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWeigh_Click_1(object sender, EventArgs e)
        {

            try
            {

                // infraredGratingHelper.Open();
                weighNow = Convert.ToDouble(lbTareQuantity.Text.Trim());
                ShowLedClient(TipsStringHelper.dqzl + weighNow + "吨", EnumHelper.LCCWLX.information);

                Thread.Sleep(1000);
                //判断车辆重量是否达标
                if (weighNow < weighPK)
                {
                    MessageThrow(TipsStringHelper.zlbdb, "重量");
                }
                if (string.IsNullOrEmpty(txtCarNum.Text.Trim()))
                {
                    MessageThrow(TipsStringHelper.whqdcph, "称重");
                }
                //infrared operations
                //get info
                var resultDataBase = WebApiService.GetTruckYxInfo(txtCarNum.Text.Trim());
                if (resultDataBase == null)
                    MessageThrow(TipsStringHelper.xtfhsjwk + "BASE", "车辆信息");
                if (!resultDataBase.success)
                    MessageThrow(resultDataBase.msg, "车辆信息");
                if (resultDataBase.data == null)
                    MessageThrow(TipsStringHelper.xtfhsjwk + "DATA", "车辆信息");
                truckYxInfo = resultDataBase.data;
                if (truckYxInfo.yxState == SysDefinitionEnum.YxState.称重_发 ||
                    truckYxInfo.yxState == SysDefinitionEnum.YxState.称重_收
                    )
                {
                    bool res = ShowMessageBox(TipsStringHelper.sfdccz, "重复称重");
                    if (!res)
                    {
                        MessageThrow(TipsStringHelper.dqczbbyx, "重复称重");
                    }
                }
                //infrared operations
                InfraredO();

                //get car infomation
                //truckYxInfo = WebApiService.GetTruckYxInfo(truckYxInfo.truckNo).data;

                //weighing ->get data from weighing

                // string kds = txtTonnageDeduction.Text.Trim();
                //截图
                pictureId = JQYSSC();
                if (string.IsNullOrWhiteSpace(pictureId))
                {
                    MessageThrow(TipsStringHelper.tpclyc, "图片处理");
                }

                //judge type（销售，采购）
                GetWeigh();
                this.Invoke(new Action(() =>
                {
                    txtGrossWeight.Text = weighNow.ToString();
                }));
                if (truckYxInfo.sendType == SysDefinitionEnum.SendType.销售)
                {
                    CreateList();

                    //车辆信息赋值
                    var infoRes = WebApiService.GetTruckYxInfo(txtCarNum.Text.Trim());
                    if (!infoRes.success)
                    {
                        MessageThrow(TipsStringHelper.scbdhqsjyc, "生成榜单");
                    }
                    truckYxInfo = infoRes.data;
                    Print.TruckYxInfo = truckYxInfo;
                    SetText();

                    //leave factory area
                    CarOut();


                    //if (truckYxInfo.yxState != SysDefinitionEnum.YxState.入场_收)
                    //{
                    //    MessageThrow(TipsStringHelper.byxzc, "称重");
                    //}
                    //get weigh
                    // GetWeigh();
                    //unload goods
                    //UnloadGoods();

                }
                //else
                //{
                //    //if (truckYxInfo.yxState != SysDefinitionEnum.YxState.装车_发)
                //    //{
                //    //    MessageThrow(TipsStringHelper.byxzc, "称重");
                //    //    return;
                //    //}
                //    //get weigh
                //   // GetWeigh();
                //    //creat list
                //   // CreateList();
                //    //leave factory area
                //    //CarOut();
                //}
                //infraredGratingHelper.Close();
                //Thread.Sleep(3000);
                //// OpenMen();
                //SetCarNum();
                OptionsSuccess("称重成功,请下磅");
            }
            catch (Exception ex)
            {
                //infraredGratingHelper.Close();
                _Led_Messahge_Log(ex);
                // Thread.Sleep(2000);
                return;
            }

        }
        #endregion
        /// <summary>
        /// 客户端提示操作赋值
        /// </summary>
        /// <param name="str"></param>
        /// <param name="cCWLX"></param>
        void ClientShowMessage(string str, EnumHelper.LCCWLX cCWLX)
        {
            this.Invoke(new Action(() =>
            {
                switch (cCWLX)
                {
                    case EnumHelper.LCCWLX.information:
                        labelMessageShow.ForeColor = Color.Green;
                        break;
                    case EnumHelper.LCCWLX.warning:
                        labelMessageShow.ForeColor = Color.YellowGreen;
                        break;
                    case EnumHelper.LCCWLX.error:
                        labelMessageShow.ForeColor = Color.Red;
                        break;
                    default:
                        break;
                }
                labelMessageShow.Text = str;
            }));
        }
        /// <summary>
        /// 显示弹窗，并返回弹窗结果
        /// </summary>
        /// <param name="str"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        bool ShowMessageBox(string str, string title)
        {
            bool suc = false;
            var res = MessageBox.Show(str, title, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (res == DialogResult.OK)
            {
                suc = true;
            }
            return suc;
        }
        /// <summary>
        /// led显示-弹窗-写操作日志
        /// </summary>
        /// <param name="s"></param>
        void _Led_Messahge_Log(Exception ex)
        {
            string s = ex.Message;
            var arr = s.Split('|');
            string str = arr[0];
            string title = "";
            if (arr.Length > 1)
                title = arr[1];
            ShowLedClient(str, EnumHelper.LCCWLX.error);
            Common.Log4.LogManage.WriteErr(ex.ToString());
            SFYXXB = true;
            // ClientShowMessage(s, EnumHelper.LCCWLX.error);
            //MessageBox.Show(str, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #region MyRegion
        private int GrossWeightOpera()
        {
            string[] imgUrl = new string[3];
            int num = 0;
            while (num < 20)
            {
                Thread.Sleep(500);
                if (isInfraredStatus)
                    break;
                num++;
            }

            if (!isInfraredStatus)
            {
                //led.LedPaly(MyCustomConfig.ledSmallEnterConfig.IpStr, "请将车辆停放在红外以内");
                //红外异常
                return -2;
            }

            if (realGrossWeight > ratedLoad * 0.6m)
            {
                //ledMsg = "毛重:" + realGrossWeight + "\n"
                //    + "限重:" + txtRatedLoad.Text + "\n"
                //    + "超重:" + txtOverload.Text;
                //led.LedPaly(MyCustomConfig.ledSmallEnterConfig.IpStr, ledMsg);

                if (isOverload)
                {
                    //led.LedPaly(MyCustomConfig.ledSmallEnterConfig.IpStr, ledMsg + "车辆超重,称重失败");
                    return -3;
                }

                if (IsOpenVideo)
                {
                    //cameraPlayVideo1.CapturePic = "1";
                    //string imgPath = cameraPlayVideo1.CapturePic;
                    //if (imgPath.Length > 2)
                    //{
                    //    imgUrl[0] = WebApiService.HttpUploadFile(imgPath, "", out errorStr);
                    //    if (!string.IsNullOrEmpty(errorStr))
                    //        imgUrl[0] = "";
                    //}
                }

                GrossWeightDto weightDto = new GrossWeightDto()
                {
                    CardNum = cardNum,
                    GrossWeight = realGrossWeight,
                    TruckNum = truckNum,
                    WeighType = SysDefinitionEnum.WeighType.Automatic,
                    ImageUrl = imgUrl
                };

                // ApiResponseDto tareDto = WebApiService.CheckGrossWeight(weightDto, out errorStr);
                //if (!tareDto.Success)
                //{
                //    //led.LedPaly(MyCustomConfig.ledSmallEnterConfig.IpStr, tareDto.Msg);
                //    return -1;
                //}

                return 1;
            }
            return 0;
        }
        #endregion

        #region timer轮询读取，资源清除
        /// <summary>
        ///timer轮询读取，资源清除
        /// </summary>
        private void ReadPollingClear(bool isDelay)
        {
            //if (isDelay)
            //{
            //    int count = 0;
            //    while (grossWeight > 0.5m)
            //    {
            //        if (count >= 30)
            //            break;
            //        count++;
            //        await Task.Delay(1000);
            //    }

            //    //await Task.Delay(25000);
            //    isRedLight = false;
            //    btnClearInfo_Click(null, null);
            //    //var existsed = listTruckData.Where(x => x.TrackNum == truckNum).FirstOrDefault();

            //    listTruckData.Clear();
            //    listCardData.Clear();
            //    led.LedSmallInitialize(MyCustomConfig.ledSmallEnterConfig.IpStr);
            //    led.LedPaly(MyCustomConfig.ledSmallEnterConfig.IpStr, "请缓慢开上地磅，准备称重");
            //    cardNum = "";
            //    truckNum = "";
            //    trafficLight.LightOff();
            //    trafficLight.RedLight();
            //    GC.Collect();
            //}
            //else
            //{
            //    await Task.Delay(3000);
            //}
        }

        #endregion

        #region 除皮按钮事件
        /// <summary>
        /// 除皮按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSkinRemoval_Click_1(object sender, EventArgs e)
        {
            try
            {
                // infraredGratingHelper.Open();
                weighNow = Convert.ToDouble(lbTareQuantity.Text.Trim());
                ShowLedClient(TipsStringHelper.dqzl + weighNow + "吨", EnumHelper.LCCWLX.information);

                Thread.Sleep(1000);
                //判断车辆重量是否达标
                if (weighNow < weighPK)
                {
                    MessageThrow(TipsStringHelper.zlbdb, "重量");
                }
                if (string.IsNullOrEmpty(txtCarNum.Text.Trim()))
                {
                    MessageThrow(TipsStringHelper.whqdcph, "除皮");
                }
                //infrared operations
                InfraredO();
                //get info
                var resultDataBase = WebApiService.GetTruckYxInfo(txtCarNum.Text.Trim());
                if (resultDataBase == null)
                    MessageThrow(TipsStringHelper.xtfhsjwk + "BASE", "车辆信息");
                if (!resultDataBase.success)
                    MessageThrow(resultDataBase.msg, "车辆信息");
                if (resultDataBase.data == null)
                    MessageThrow(TipsStringHelper.xtfhsjwk + "DATA", "车辆信息");
                truckYxInfo = resultDataBase.data;
                if (truckYxInfo.yxState == SysDefinitionEnum.YxState.除皮_发 ||
                    truckYxInfo.yxState == SysDefinitionEnum.YxState.除皮_收
                    )
                {
                    bool res = ShowMessageBox(TipsStringHelper.sfdccp, "重复除皮");
                    if (!res)
                    {
                        MessageThrow(TipsStringHelper.dqczbbyx, "重复除皮");
                    }
                }
                //截图
                pictureId = JQYSSC();
                if (string.IsNullOrWhiteSpace(pictureId))
                {
                    MessageThrow(TipsStringHelper.tpclyc, "图片处理");
                }
                //在除皮时候如果是采购的车辆，必须传矿发量
                if (truckYxInfo.sendType == SysDefinitionEnum.SendType.采购)
                {
                    string kfl = textBoxKFL.Text;
                    if (Convert.ToDecimal(kfl) <= 0)
                    {
                        MessageThrow(TipsStringHelper.kflbnwk, "矿发量");
                    }
                }
                //judge type
                CutTare();
                this.Invoke(new Action(() =>
                {
                    txtTare.Text = weighNow.ToString();
                }));

                if (truckYxInfo.sendType == SysDefinitionEnum.SendType.采购)
                {
                    //creat list
                    CreateList();

                    //车辆信息赋值
                    var infoRes = WebApiService.GetTruckYxInfo(txtCarNum.Text.Trim());
                    if (!infoRes.success)
                    {
                        MessageThrow(TipsStringHelper.scbdhqsjyc, "生成榜单");
                    }
                    truckYxInfo = infoRes.data;
                    Print.TruckYxInfo = truckYxInfo;
                    SetText();

                    //leave factory area
                    CarOut();

                }
                //else//sale
                //{
                //    //if (truckYxInfo.yxState == SysDefinitionEnum.YxState.入场_发 || truckYxInfo.yxState == SysDefinitionEnum.YxState.除皮_发)
                //    //{
                //    //    MessageThrow(TipsStringHelper.cpcxcw, "除皮");
                //    //}
                //    //cut tare
                //    //CutTare();
                //}

                // infraredGratingHelper.Close();
                OptionsSuccess("除皮成功,请下磅");

                // Thread.Sleep(3000);
                //SetCarNum();
            }
            catch (Exception ex)
            {
                //infraredGratingHelper.Close();
                _Led_Messahge_Log(ex);
                // Thread.Sleep(2000);

                return;
            }

        }
        #endregion
        /// <summary>
        /// 是否允许下磅
        /// </summary>
        bool SFYXXB = false;
        /// <summary>
        /// 操作完成的之后的提升的提示。
        /// </summary>
        /// <param name="successMessage"></param>
        void OptionsSuccess(string successMessage)
        {
            // ClientShowMessage(successMessage, EnumHelper.LCCWLX.information);
            //var res = MessageBox.Show(successMessage, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //MessageBox.Show(successMessage);
            this.Invoke(new Action(() =>
            {

                //if (res == DialogResult.OK)
                //{
                ShowLedClient(successMessage, EnumHelper.LCCWLX.information);
                SFYXXB = true;
                var carNumTemp = carNumList.Where(p => p.Key == txtCarNum.Text.Trim()).FirstOrDefault();
                if (carNumTemp.Value == 2)
                {
                    OpenMen();
                }
                //var carNumTemp = carNumList.Where(p => p.Key == txtCarNum.Text.Trim()).FirstOrDefault();
                //if (!string.IsNullOrWhiteSpace(carNumTemp.Key ?? ""))
                //{
                //    //carNumList.Remove(carNumTemp.Key);
                //    if (carNumTemp.Value == 2)
                //    {
                //        OpenMen();
                //    }
                //}
                //SetCarNum();
                // ClearText();



                // }
            }));

        }

        #region icon图标右键点击事件
        /// <summary>
        /// icon图标右键点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exit_Click_1(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

        #region 盘煤的称重
        /// <summary>
        /// 盘煤称重按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SFYXXB = true;
                TurnCoal();
                //SetCarNum();
                //open the door
                // cameraHelperQ.BarrierGateControl(cmdFlag: 1);
                OptionsSuccess("盘煤称重成功,请下磅");
            }
            catch (Exception ex)
            {
                /// infraredGratingHelper.Close();
                _Led_Messahge_Log(ex);
                //Thread.Sleep(2000);
                return;
            }
        }
        #endregion

        #region 系统硬件保存设置
        /// <summary>
        /// 系统硬件保存设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            /**/
        }
        #endregion

        #region 截取图片压缩上传返回图片id一步到位
        /// <summary>
        /// 截取图片压缩上传返回图片id一步到位
        /// </summary>
        /// <returns></returns>
        private string JQYSSC()
        {
            if (!cameraIsOpen)
            {
                Common.Log4.LogManage.WriteErr("摄像头未打开");
                return null;
            }
            string guid = Guid.NewGuid().ToString();
            ReBaseModel reBaseModel = cameraHelperG.GetPucture(guid);//抓图
            if (!reBaseModel.res)
            {
                Common.Log4.LogManage.WriteErr(reBaseModel.Msg);
                return null;
            }
            string filePathS = ImgHelper.CompressImg(sFile: reBaseModel.Msg);//压缩图片
            if (string.IsNullOrWhiteSpace(filePathS))
            {
                return null;
            }
            string errStr;
            string pictureId = WebApiService.HttpUploadFile(filePathS, out errStr);//上传图片 到服务器
            if (!string.IsNullOrWhiteSpace(errStr))
            {
                Common.Log4.LogManage.WriteErr(errStr);
                return null;
            }
            return pictureId;

        }
        //前截图
        private string JQYSSCYTJQ()
        {
            if (!cameraIsOpen)
            {
                return null;
            }
            string guid = Guid.NewGuid().ToString();
            ReBaseModel reBaseModel = cameraHelperQ.GetPucture(guid);//抓图
            if (!reBaseModel.res)
            {
                return null;
            }
            string filePathS = ImgHelper.CompressImg(sFile: reBaseModel.Msg);//压缩图片
            if (string.IsNullOrWhiteSpace(filePathS))
            {
                return null;
            }
            string errStr;
            string pictureId = WebApiService.HttpUploadFile(filePathS, out errStr);//上传图片 到服务器
            if (!string.IsNullOrWhiteSpace(errStr))
            {
                return null;
            }
            return pictureId;

        }
        //后截图
        private string JQYSSCYTJH()
        {
            if (!cameraIsOpen)
            {
                return null;
            }
            string guid = Guid.NewGuid().ToString();
            ReBaseModel reBaseModel = cameraHelperH.GetPucture(guid);//抓图
            if (!reBaseModel.res)
            {
                return null;
            }
            string filePathS = ImgHelper.CompressImg(sFile: reBaseModel.Msg);//压缩图片
            if (string.IsNullOrWhiteSpace(filePathS))
            {
                return null;
            }
            string errStr;
            string pictureId = WebApiService.HttpUploadFile(filePathS, out errStr);//上传图片 到服务器
            if (!string.IsNullOrWhiteSpace(errStr))
            {
                return null;
            }
            return pictureId;

        }
        #endregion

        private void RemovalAndWeigh_SizeChanged(object sender, EventArgs e)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(this.Controls[0]);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);

            }
        }
        /// <summary>
        /// 打开摄像头出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenVideo2_Click_1(object sender, EventArgs e)
        {
            //string ip = "192.168.3.64";
            var res = cameraHelperH.ManualOne(picVideo2);
            if (!res.res)
                ShowMessageAndLed(res.Msg, "打开视频");
            else
            {
                ClientShowMessage("视频打开成功", EnumHelper.LCCWLX.information);
            }
        }

        /// <summary>
        /// 打印磅单按钮事件-预览打印详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            Print print = new Print(txtCarNum.Text);
            print.ShowDialog();
        }

        /// <summary>
        /// 注销按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label5_Click(object sender, EventArgs e)
        {
            //this.Close();
            //MainForm mainForm = new MainForm();
            //mainForm.ShowDialog();

            if (MessageBox.Show("确定注销？", "提示", MessageBoxButtons.YesNoCancel,
             MessageBoxIcon.Question) == DialogResult.Yes)
            {
                MainForm mainForm = new MainForm();
                mainForm.InitName = false;
                mainForm.ControlBox = false;
                mainForm.MinimizeBox = false;
                //var a = login.Controls["panel1"].Controls["textBoxUserName"];
                //a.Text = "asd";
                //login.Controls["panel1"].Controls["textBoxPassWord"].Text = "";
                mainForm.ShowDialog();

            }
            labelDQYH.Text = "当前用户：" + AppSession.UserInfo.UserName;
        }
        /// <summary>
        /// open the door
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button3_Click(object sender, EventArgs e)
        {
            string temp = "";
            //截图
            string pictureG = JQYSSC();
            string pictureQ = JQYSSCYTJQ();
            string pictureH = JQYSSCYTJH();
            if (!string.IsNullOrEmpty(pictureG))
            {
                temp += pictureG + ",";
            }
            if (!string.IsNullOrEmpty(pictureQ))
            {
                temp += pictureQ + ",";
            }
            if (!string.IsNullOrEmpty(pictureQ))
            {
                temp += pictureH;
            }
            if (!string.IsNullOrEmpty(temp))
            {
                temp = temp.TrimEnd(',');
                var resM = WebApiService.Release(Convert.ToInt32(AppConfigHelper.GetAppSettings("weighId")), temp);
                if (resM.success == false)
                {
                    Common.Log4.LogManage.WriteErr(resM.msg);
                }
            }
            bool openState = cameraHelperQ.BarrierGateControl(1);
            if (!openState)
            {
                ShowMessageAndLed("道闸开启失败！", "开启道闸");
            }
        }
    }
}
